import {history} from 'umi'
import {Toast} from 'antd-mobile'
import {Http, mergeRoute, storage} from '@/utils'

let extraRoutes
const token = storage.get('token')

export function onRouteChange(route) {
  const nowPath = route.routes[0].routes.filter(item => item.path === route.location.pathname)
  const isLogin = storage.get('token')

  if (nowPath.length === 1 && nowPath[0].auth && !isLogin) {
    Toast.fail('请先登录')
    history.push({
      pathname: '/login'
    })
  }
}

export function patchRoutes({routes}) {
  mergeRoute(routes[0].routes, extraRoutes || [])
}

export function render(oldRender) {
  if (token) {
    Http({url: '/user/checkToken'}).then((data) => {
      const {token, user, menus} = data
      storage.set('token', token)
      storage.set('user', user)
      storage.set('menus', menus)
      extraRoutes = menus
      oldRender()
    }, message => {
      Toast.fail(message)
      storage.clear()
      history.push('/login')
      oldRender()
    })
  } else {
    history.push('/login')
    oldRender()
  }
}
